<template>
  <div class="user-courses-container">
    <frontend-header />
    
    <div class="container">
      <div class="page-header">
        <h1>我的课程</h1>
        <p>继续您的学习之旅，跟踪学习进度</p>
      </div>
      
      <div class="content-wrapper">
        <!-- 侧边导航 -->
        <div class="sidebar">
          <div class="user-info-card">
            <div class="avatar-container">
              <img :src="userInfo.avatar" :alt="userInfo.name" class="user-avatar">
            </div>
            <h3>{{ userInfo.name || userInfo.username }}</h3>
            <p class="user-stats">共 {{ courses.length }} 门课程</p>
          </div>
          
          <el-menu
            :default-active="activeMenu"
            class="profile-menu"
            router
          >
            <el-menu-item index="/user/profile">
              <el-icon><User /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="/user/courses">
              <el-icon><VideoPlay /></el-icon>
              <span>我的课程</span>
            </el-menu-item>
            <el-menu-item index="/user/orders">
              <el-icon><Document /></el-icon>
              <span>我的订单</span>
            </el-menu-item>
          </el-menu>
        </div>
        
        <!-- 主要内容 -->
        <div class="main-content">
          <div class="course-filters">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索课程名称"
              prefix-icon="Search"
              class="search-input"
              >
              <template #append>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
            <el-select v-model="filterType" placeholder="课程类型" class="filter-select">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="type in courseTypes" :key="type.id" :label="type.name" :value="type.id"></el-option>
            </el-select>
            <el-select v-model="sortBy" placeholder="排序方式" class="filter-select">
              <el-option label="购买时间（最新）" value="recent"></el-option>
              <el-option label="购买时间（最早）" value="oldest"></el-option>
            </el-select>
          </div>
          
          <div class="courses-grid" v-if="courses.length> 0">
            <el-card v-for="course in courses" :key="course.id" shadow="hover" class="course-card">
              <div class="course-content">
                <div class="course-image-container">
                  <img :src="course.image" :alt="course.name" class="course-image">
                </div>
                <div class="course-info">
                  <h3 class="course-title">{{ course.name }}</h3>
                  <p class="course-type">{{ getCourseTypeName(course.typeId) }}</p>
                  <div class="course-stats">
                    <span class="stat-item">
                      <el-icon><VideoPlay /></el-icon>
                      {{ course.totalSections }} 小节
                    </span>
                    <span class="stat-item">
                      <el-icon><Calendar /></el-icon>
                      {{ formatDate(course.createTime) }}
                    </span>
                  </div>
                  <div class="course-actions">
                    <el-button type="primary" @click="goToLearn(course.id)">继续学习</el-button>
                    <el-button @click="viewCourseDetail(course.id)">课程详情</el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          <div v-else class="empty-courses">
            <el-empty description="暂无已购课程" />
            <el-button type="primary" @click="goToBrowseCourses">去选课</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <FrontendFooter />
  </div>
</template>

<script setup>
import FrontendHeader from '../../components/FrontendHeader.vue'
import FrontendFooter from '../../components/FrontendFooter.vue'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { User, VideoPlay, Document, Search, Clock, Calendar } from '@element-plus/icons-vue'
import {coursesByUid} from "@/api/Course.js";
import {queryAll} from "@/api/CourseTypes.js";

const route = useRoute()
const router = useRouter()

// 用户信息
const userInfo = reactive({
  id: '',
  username: '',
  name: '',
  avatar: 'https://picsum.photos/100/100?random=1'
})

// 课程数据
const courses = ref([])
//课程类型
const courseTypes = ref([])

// 筛选和搜索
const searchKeyword = ref('')
const filterType = ref('')
const sortBy = ref('recent')



// 计算当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})



// 加载用户信息
const loadUserInfo = () => {
  // 这里应该调用API获取用户信息
  // 暂时使用模拟数据
  const storedUserInfo = sessionStorage.getItem('userInfo')
  if (storedUserInfo) {
    const parsedUserInfo = JSON.parse(storedUserInfo)
    Object.assign(userInfo, {
      ...parsedUserInfo,
      name: parsedUserInfo.name || parsedUserInfo.username
    })
  }
}

const queryByUser=()=>{
  //获取用户id-->sessionStorage
  const user = sessionStorage.getItem("userInfo");
  //user是一个字符串-->转成json对象 JSON.parse(user);
  // 这里应该调用API获取用户已购买的课程
  coursesByUid({
    uid:JSON.parse(user).id,
    courseName:searchKeyword.value,
    courseType:filterType.value,
    sortBy:sortBy.value
  }).then(res=>{
    console.log(res)
    courses.value = res.data
  })
}
// 加载课程数据
const loadCourses = () => {
  queryByUser()
  //查询类别信息
  queryAll().then(res=>{
    courseTypes.value = res.data
  })
}

//条件查询
const handleSearch=()=>{
  queryByUser()
}


// /获取课程类型名称
const getCourseTypeName = (typeId) => {
  const type = courseTypes.value.find(t => t.id === typeId)
  return type ? type.name : '未知类型'
}

// 格式化时长
const formatDuration = (minutes) => {
  const hours = Math.floor(minutes / 60)
  const mins = minutes % 60
  if (hours > 0) {
    return `${hours}小时${mins > 0 ? mins + '分钟' : ''}`
  }
  return `${mins}分钟`
}

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// 去学习
const goToLearn = (courseId) => {
  router.push(`/course/learn/${courseId}`)
}

// 查看课程详情
const viewCourseDetail = (courseId) => {
  router.push(`/course/detail/${courseId}`)
}

// 去浏览课程
const goToBrowseCourses = () => {
  router.push('/courses')
}


// 处理菜单选择
const handleMenuSelect = (key) => {
  router.push(key)
}

// 页面加载时获取数据
onMounted(() => {
  loadUserInfo()
  loadCourses()
})
</script>

<style scoped>
.user-courses-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 0;
  padding-bottom: 200px;
  position: relative;
  overflow: visible;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 16px;
  opacity: 0.9;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.sidebar {
  width: 280px;
  flex-shrink: 0;
}

.user-info-card {
  background-color: white;
  border-radius: 8px;
  padding: 30px 20px;
  text-align: center;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.avatar-container {
  margin-bottom: 20px;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info-card h3 {
  margin: 0 0 8px 0;
  color: #303133;
}

.user-stats {
  color: #606266;
  font-size: 14px;
  margin: 0;
}

.profile-menu {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.main-content {
  flex: 1;
  overflow: visible;
}

.course-filters {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 200px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}

/* 使用更具体的选择器确保样式优先级 */
:deep(.el-card.course-card) {
  height: auto !important;
  min-height: 450px !important;
  transition: transform 0.3s, box-shadow 0.3s;
  overflow: visible !important;
  display: block !important;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.course-content {
  display: flex;
  flex-direction: column;
  height: auto !important;
  min-height: 400px;
  padding: 15px;
  width: 100%;
  box-sizing: border-box;
}

.course-image-container {
  position: relative;
  margin-bottom: 15px;
}

.course-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.course-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 180px;
}

.course-title {
  font-size: 18px;
  margin: 0 0 8px 0;
  color: #303133;
  line-height: 1.5;
  height: auto;
  min-height: 54px;
  overflow: visible !important;
  display: block !important;
  -webkit-line-clamp: unset !important;
}

.course-type {
  color: #667eea;
  font-size: 14px;
  margin-bottom: 12px;
}

.course-stats {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #909399;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.course-actions {
  margin-top: auto;
  display: flex;
  gap: 10px;
  padding-top: 15px;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
}

/* 确保按钮不会被截断 */
.course-actions .el-button {
  white-space: nowrap;
  flex: 1;
}

/* 确保内容不会被隐藏 */
:deep(.el-card__body) {
  padding: 0 !important;
  overflow: visible !important;
}

.empty-courses {
  background-color: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-courses .el-button {
  margin-top: 20px;
}



@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
  }
  
  .profile-menu {
    display: flex;
    justify-content: space-around;
  }
  
  .course-filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
  
  .courses-grid {
    grid-template-columns: 1fr;
  }
  
  .course-stats {
    flex-direction: column;
    gap: 8px;
  }
}
</style>